extern "C" {
#include	<luajit.h>
#include	<lualib.h>
#include	<lauxlib.h>
}

#include	"../router.h"

namespace LuaApi { namespace LuaRouter {
	static int Get(lua_State * pL) {
		std::string sUrl = lua_tostring(pL, 1);

		lua_pushvalue(pL, 2);
		int nRef = luaL_ref(pL, LUA_REGISTRYINDEX);
		Router::Get().Register("GET", sUrl, nRef);
		return 0;
	}

	static int Post(lua_State * pL) {
		std::string sUrl = lua_tostring(pL, 1);

		lua_pushvalue(pL, 2);
		Router::Get().Register("POST", sUrl, luaL_ref(pL, LUA_REGISTRYINDEX));
		return 0;
	}

	static int Put(lua_State * pL) {
		std::string sUrl = lua_tostring(pL, 1);

		lua_pushvalue(pL, 2);
		Router::Get().Register("PUT", sUrl, luaL_ref(pL, LUA_REGISTRYINDEX));
		return 0;
	}

	static int Delete(lua_State * pL) {
		std::string sUrl = lua_tostring(pL, 1);

		lua_pushvalue(pL, 2);
		Router::Get().Register("DELETE", sUrl, luaL_ref(pL, LUA_REGISTRYINDEX));
		return 0;
	}

	static int Any(lua_State * pL) {
		std::string sUrl = lua_tostring(pL, 1);

		lua_pushvalue(pL, 2);
		Router::Get().Register("ANY", sUrl, luaL_ref(pL, LUA_REGISTRYINDEX));
		return 0;
	}

} }

void RegisterApi_Router(lua_State * pL) {
	lua_newtable(pL);

	lua_pushcfunction(pL, &LuaApi::LuaRouter::Get);
	lua_setfield(pL, -2, "get");

	lua_pushcfunction(pL, &LuaApi::LuaRouter::Post);
	lua_setfield(pL, -2, "post");

	lua_pushcfunction(pL, &LuaApi::LuaRouter::Put);
	lua_setfield(pL, -2, "put");

	lua_pushcfunction(pL, &LuaApi::LuaRouter::Delete);
	lua_setfield(pL, -2, "delete");

	lua_pushcfunction(pL, &LuaApi::LuaRouter::Any);
	lua_setfield(pL, -2, "any");

	lua_setglobal(pL, "router");
}